from tabulate import tabulate
import pandas as pd
import requests

taskStatusMap = {
    "60418b08c679e20044c09c0c": "其他功能解决",
    "64af9ca33bb6c5ae1239f98e": "待开发评估",
    "654da2f56c338454318df4de": "待发布SIT(组内环境已测)",
    "5e0dabc57d161c00217800b8": "开发中",
    "6604cf0816117c37565adb54": "待开发",
    "5e0db98a8fc7b60022d301c6": "待组内评审",
    "6535cfab96d44880e05a51b1": "待测试",
    "6535cfab96d44880e05a51b4": "测试中",
    "5f40cf2267d6500044ec1a29": "待分析",
    "6535cfab96d44880e05a51b7": "已发布SIT(合入release部署)",
    "5e0dabc57d161c00217800b9": "已发布生产",
    "60418b08c679e20044c09c0c": "其他功能已解决",
    "614407e924ae43003fd05019": "已完成（不发版）",
    "603ddbf166272e0044b3d934": "已发布UAT",
    "5e0dabc57d161c00217800b7": "待产品内审",
    "5e0db97739a39700233b0199": "待审阅",
    "6340edfabb167700408b7339": "经评估无法实现",
    "65e80e978ec65144610baca1": "待架构组评审",
}
dev_day_benchmark = {
    "202501": 16,
    "202502": 15,
    "202503": 16,
    "202504": 15,
}
sprintMap = {
    "202412-2": "202501",
    "202501-1": "202501",
    "202501-2": "202502",
    "202502-1": "202502",
    "202502-2": "202503",
    "202503-1": "202503",
    "202503-2": "202504",
    "202504-1": "202504",
    "202504-2": "202505",
    "202505-1": "202505",
    "202505-2": "202506",
    "202506-1": "202506",
    "202506-2": "202507",
    "202507-1": "202507",
    "202507-2": "202508",
    "202508-1": "202508",
    "202508-2": "202509",
    "202509-1": "202509",
    "202509-2": "202510",
    "202510-1": "202510",
    "202510-2": "202511",
    "202511-1": "202511",
    "202511-2": "202512",
    "202512-1": "202512",
    "202512-2": "202601",
    "202601-1": "202601",
    "202601-2": "202602",
}
# sprintList = ['202412-2','202501-1']
sprintList = [
    "202412-2",
    "202501-1",
    "202501-2",
    "202502-1",
    "202502-2",
    "202503-1",
    "202503-2",
    "202504-1",
    "202504-2",
    "202505-1",
]
data = []
for sprint in sprintList:
    # if sprint != '202412-2':
    #   continue
    res = requests.get(
        "https://quality-tools.maycur.com//teambition_script/sprint/task/?name="
        + sprint
    )
    d = res.json()["data"]
    data.extend(d)
index = 0
tasks = []
fatherTasksId = []
for d in data:
    if "parentTaskId" in d and d["parentTaskId"] not in fatherTasksId:
        fatherTasksId.append(d["parentTaskId"])
for d in data:
    if taskStatusMap.get(d["tfsId"], "unknow") == "其他功能已解决":
        continue
    if "executorName" in d:
        customFields = d["customfields"]
        task = {
            "id": d["id"],
            "taskNo": "DB-" + str(d["uniqueId"]),
            "executorName": d["executorName"],
            "sprintName": d["sprintName"],
            "publishSprint": sprintMap.get(d["sprintName"], "unknow"),
            "status": taskStatusMap.get(d["tfsId"], "unknow"),
            "parentId": d.get("parentTaskId", None),
            "isFather": d["id"] in fatherTasksId,
        }
        task["frontend"] = "未分配"
        task["backend"] = "未分配"
        task["test"] = "未分配"
        task["frontend_day"] = 0
        task["backend_day"] = 0
        task["test_day"] = 0
        for cf in customFields:
            if cf.get("value", None) is None:
                continue
            if len(cf["value"]) == 0:
                continue
            if cf["cfId"] == "660be84c797f388d73107b34":
                task["frontend"] = cf["value"][0]["title"]
            elif cf["cfId"] == "660be86cfdae364d32426542":
                task["backend"] = cf["value"][0]["title"]
            elif cf["cfId"] == "660be8a675863a6977f65356":
                task["test"] = cf["value"][0]["title"]
            elif cf["cfId"] == "62de3ebad7ab965fbdf6c144":
                task["frontend_day"] = float(cf["value"][0]["title"])
            elif cf["cfId"] == "62de3ed2d51a977b23f42b6b":
                task["backend_day"] = float(cf["value"][0]["title"])
            elif cf["cfId"] == "62de3ee92d8f775082f164f8":
                task["test_day"] = float(cf["value"][0]["title"])
        tasks.append(task)

df = pd.DataFrame(tasks)
df = df[df["isFather"] != True]
# df = df[(df['isFather'] != True)&(df['frontend'].isin(['未分配'])) & (df['frontend_day'] >0)]
# df.to_csv('./output/frontend_unassigned.csv',index=False)
# frontend_df = df.groupby(['publishSprint','frontend'])['frontend_day'].sum()
# frontend_df.to_csv('./output/frontend_day.csv')
# backend_df = df.groupby(['publishSprint','backend'])['backend_day'].sum()
# backend_df.to_csv('./output/backend_day.csv')
# test_df = df.groupby(['publishSprint','test'])['test_day'].sum()
# test_df.to_csv('./output/test_day.csv')


""" test block start"""
specify_sprint = "202501"
benchmark = dev_day_benchmark[specify_sprint]
mask = df["publishSprint"] == specify_sprint
frontend_df = (
    df[mask]
    .groupby(["publishSprint", "frontend"])["frontend_day"]
    .sum()
    .to_frame(name="sum")
)
frontend_df["is_exceed_benchmark"] = frontend_df["sum"] > benchmark
print(frontend_df)
# df_specify_sprint.to_csv('./output/specify_sprint_day.csv',index=False)
""" test block end """

# debug print
# print(df)
# print(fatherTasksId)
# print(df)
# print(df.head())
# ['accomplishTime', 'ancestorIds', 'content', 'created', 'creatorId', 'customfields', 'dueDate', 'executorId', 'id', 'involveMembers', 'isArchived',
#  'isDone', 'note', 'pos', 'priority', 'progress', 'projectId', 'recurrence', 'sfcId', 'sourceId', 'sprintId', 'stageId', 'startDate', 'storyPoint',
# 'tagIds', 'tasklistId', 'tfsId', 'uniqueId', 'updated', 'visible', 'sprintName', 'executorName']

# print(df.dtypes)
# print(df[df['isFather'] == True])
# print(df[df['frontend']=='鲁剑刚'])
# print(df.groupby(['publishSprint','frontend'])['frontend_day'].sum())
# print(df.groupby(['publishSprint','backend'])['backend_day'].sum())
# print(df.groupby(['publishSprint','test'])['test_day'].sum())
# print(tabulate(df, headers='keys', tablefmt='pretty'))
